/*
Uninclude: Tool for detecting unused #included files in C and C++ code.
    Copyright (C) 2012  Daniel Gutson, FuDePAN

    Uninclude is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version./

    Uninclude is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Uninclude.  If not, see <http://www.gnu.org/licenses/>.

    This is an utility to create temporary C/C++ files.
*/

#ifndef TMP_FILE_H
#define TMP_FILE_H

#include <assert.h>
#include <unistd.h>
#include <string>
#include <fstream>
#include "uninclude/dir_utils.h"

class TmpFile
{
protected:
    string fileName;

    // includes the dot
    static string getNameExt(const string& fileName)
    {
        const string::size_type lastDot = fileName.find_last_of('.');
        if ( lastDot != string::npos )
            return fileName.substr(lastDot);
        else
            return string();
    }

public:
    TmpFile(){}
    TmpFile(const string& original)
    {
        create(original);
    }

    ~TmpFile()
    {
        if (!fileName.empty())
            unlink(fileName.c_str());
    }

    void create(const string& original)
    {
        assert(fileName.empty());

        string dir;

        splitDirFile(original, dir, fileName);
        fileName.insert(0, dir + "__uninc_tmp_" );
    }

    const string& getName() const
    {
        return fileName;
    }
};

class CppTmpFile : public TmpFile
{
public:
    CppTmpFile(){}
    CppTmpFile(const string& original) : TmpFile(original) {}

    void replaceLine(const string& original, size_t lineNumber, const string& newLine)
    {
        ifstream originalFile(original.c_str());
        ofstream newFile(fileName.c_str());
        string   line;
        size_t   currentLine = 0;

        if (!originalFile)
            throw "Problem opening original file.";

        //cerr << "Replacing " << fileName << ":" << lineNumber << " with " << newLine << endl;

        while(getline(originalFile, line))
        {
            currentLine++;

            if (currentLine == lineNumber)
                newFile << newLine << endl;
            else
                newFile << line << endl;
        }
    }
};

#endif

